package com.youxin.cpcenter.service.impl;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.bean.ent.MemberIdentityBean;
import com.youxin.busfoundation.bean.ent.QueryEntAdminStatusBean;
import com.youxin.busfoundation.bean.ent.RequestEntIdentifyInfo;
import com.youxin.busfoundation.bean.ent.RequestMemberIdentifyBean;
import com.youxin.busfoundation.bean.ent.RequestMemberInfo;
import com.youxin.busfoundation.bean.ent.RequestMemberInfoIdentify;
import com.youxin.busfoundation.bean.ent.RequestTrySubmitBean;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.BuildConfig;
import com.youxin.busfoundation.common.BusinessDataException;
import com.youxin.busfoundation.common.BusinessException;
import com.youxin.busfoundation.common.BusinessRuntimeException;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.common.UidGenerator;
import com.youxin.busfoundation.common.redis.RedisOperator;
import com.youxin.busfoundation.enums.EnterpriseIdentifyStatus;
import com.youxin.busfoundation.enums.EnterpriseIdentityType;
import com.youxin.busfoundation.enums.EnterpriseManagerType;
import com.youxin.busfoundation.enums.EnterprisePassStatus;
import com.youxin.busfoundation.enums.EnterpriseTryoutStatus;
import com.youxin.busfoundation.enums.MemberDeleteStatus;
import com.youxin.busfoundation.enums.MemberStatus;
import com.youxin.busfoundation.sms.SmsUtils;
import com.youxin.busfoundation.utils.DateTimeBusUtils;
import com.youxin.cpcenter.bean.MemberQueryListBean;
import com.youxin.cpcenter.bean.RequestCompanyBean;
import com.youxin.cpcenter.bean.member.MemberInfo;
import com.youxin.cpcenter.bean.member.QueryMemberInfo;
import com.youxin.cpcenter.dao.TbEntMemberIdentifyCapitalMapper;
import com.youxin.cpcenter.dao.TbEntMemberIdentifyMapper;
import com.youxin.cpcenter.dao.TbEntMemberInfoMapper;
import com.youxin.cpcenter.dao.TbEntTryoutInfoMapper;
import com.youxin.cpcenter.dao.TbMemberInfoMapper;
import com.youxin.cpcenter.model.TbCompanyInfo;
import com.youxin.cpcenter.model.TbEntLeadsStat;
import com.youxin.cpcenter.model.TbEntMemberIdentify;
import com.youxin.cpcenter.model.TbEntMemberIdentifyCapital;
import com.youxin.cpcenter.model.TbEntMemberIdentifyCapitalHis;
import com.youxin.cpcenter.model.TbEntMemberInfo;
import com.youxin.cpcenter.model.TbEntTryoutInfo;
import com.youxin.cpcenter.model.TbMemberInfo;
import com.youxin.cpcenter.service.CapitalService;
import com.youxin.cpcenter.service.CompanyInfoService;
import com.youxin.cpcenter.service.EnterpriseService;
import com.youxin.cpcenter.service.LeadsStatService;
import com.youxin.cpcenter.service.MemberNumberService;
import com.youxin.cpcenter.service.utils.MemberInfoUtils;
import com.youxin.cpcenter.utils.MemberRightsUtils;
import com.youxin.foundation.data.Tuple;
import com.youxin.foundation.db.utils.KeyGenerationUtils;
import com.youxin.foundation.interfaces.ExecuteFunction;
import com.youxin.foundation.utils.ArrayUtils;
import com.youxin.foundation.utils.RandomUtils;
import com.youxin.foundation.utils.StringUtils;

/**
 * 企业认证信息接口
 * 
 * @author yingde.cao
 *
 */
@Service("enterpriseService")
public class EnterpriseServiceImpl extends BaseServiceImpl implements EnterpriseService {

	@Autowired
	private TbEntMemberIdentifyMapper tbEntMemberIdentifyMapper;
	@Autowired
	private TbMemberInfoMapper tbMemberInfoMapper;
	@Autowired
	private TbEntTryoutInfoMapper tbEntTryoutInfoMapper;
	@Autowired
	private TbEntMemberInfoMapper tbEntMemberInfoMapper;
	@Autowired
	private TbEntMemberIdentifyCapitalMapper tbEntMemberIdentifyCapitalMapper;

	@Autowired
	private CapitalService capitalService;

	// @Autowired
	// private CompanyInfoService companyInfoService;

	/**
	 * 企业版系统认证公司
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject requestIdentify(RequestEntIdentifyInfo bean) {
		EnterpriseIdentityType identityType = EnterpriseIdentityType.valueOf(bean.getIdentifyType());
		if (identityType == null) {
			throw new BusinessDataException("企业认证类型错误");
		}
		TbEntTryoutInfo sourceEntTryoutInfo = tbEntTryoutInfoMapper.selectByPrimaryKey(bean.getId());
		if (sourceEntTryoutInfo == null) {
			throw new BusinessDataException("企业并没有申请试用");
		}
		if (sourceEntTryoutInfo.getStatus().intValue() == EnterpriseTryoutStatus.ReviewPassed.getValue()) {
			throw new BusinessDataException("企业已经申请并认证成功!");
		}

		long entMemberInfoId = KeyGenerationUtils.generateKey();
		long entIdentifyId = KeyGenerationUtils.generateKey();
		RequestCompanyBean companyBean = new RequestCompanyBean();
		companyBean.setCompanyUid(bean.getCompanyUid());

		/**
		 * 创建或更新会员信息
		 */
		TbMemberInfo memberInfo = createOrUpdateMemberInfo(bean.getMemberId(), bean.getCompanyUid(), bean.getFullName(),
				sourceEntTryoutInfo.getMobile(), sourceEntTryoutInfo.getName(), entMemberInfoId, entIdentifyId);

		/**
		 * 创建认证公司信息
		 */
		TbEntMemberIdentify identify = new TbEntMemberIdentify();
		identify.setMobile(sourceEntTryoutInfo.getMobile());
		identify.setRealName(sourceEntTryoutInfo.getName());
		identify.setPosition(sourceEntTryoutInfo.getPosition());

		TbEntMemberIdentify tbEntMemberIdentify = createOrUpdateEntIdentity(identify, memberInfo, identityType,
				bean.getCompanyUid(), bean.getFullName(), entIdentifyId, entMemberInfoId);

		updateEntTryoutInfo(memberInfo, sourceEntTryoutInfo, tbEntMemberIdentify, entMemberInfoId);
		/**
		 * 创建会员企业信息
		 */
		TbEntMemberInfo tbEntMemberInfo = createEntMemberInfo(memberInfo, tbEntMemberIdentify, identityType,
				entMemberInfoId,null);

		/**
		 * 创建会员认证资本信息
		 */
		createEntMemberIdentityCatpital(memberInfo, tbEntMemberIdentify, identityType);
		return ResponseObject.successObject();
	}

	private void sendIdentifyMessage(String mobile) {
		try {
			String message = "【商理事】尊敬用户，您的企业版账号已开通。如有疑问，请联系客服：400-806-2262";
			String result = SmsUtils.sendSms(mobile, message);
			logger.warn("send:" + String.valueOf(result));
		} catch (Exception e) {
			logger.error(e);
		}

	}

	/**
	 * OA后台提交的用户信息认证
	 * 
	 * @param bean
	 * @return
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject memberInfoIdentify(RequestMemberInfoIdentify bean) {
		EnterpriseIdentityType identityType = EnterpriseIdentityType.valueOf(bean.getIdentifyType());
		if (identityType == null) {
			throw new BusinessDataException("企业认证类型错误");
		}
		TbEntMemberIdentify memberIdentify = tbEntMemberIdentifyMapper.selectByCompanyUid(bean.getCompanyUid());
		if (memberIdentify != null) {
			throw new BusinessDataException("企业认证已被认证");
		}
		long entMemberInfoId = KeyGenerationUtils.generateKey();
		long entIdentifyId = KeyGenerationUtils.generateKey();
		RequestCompanyBean companyBean = new RequestCompanyBean();
		companyBean.setCompanyUid(bean.getCompanyUid());
		/**
		 * 创建或更新会员信息
		 */
		TbMemberInfo memberInfo = createOrUpdateMemberInfo(0, bean.getCompanyUid(), bean.getCompanyName(),
				bean.getMobile(), bean.getRealname(), entMemberInfoId, entIdentifyId);
		/**
		 * 创建认证公司信息
		 */
		TbEntMemberIdentify identify = new TbEntMemberIdentify();
		identify.setMobile(bean.getMobile());
		identify.setRealName(bean.getRealname());
		identify.setPosition(bean.getPosition());
		TbEntMemberIdentify tbEntMemberIdentify = createOrUpdateEntIdentity(identify, memberInfo, identityType,
				bean.getCompanyUid(), bean.getCompanyName(), entIdentifyId, entMemberInfoId);
		/**
		 * 创建会员企业信息
		 */
		TbEntMemberInfo tbEntMemberInfo = createEntMemberInfo(memberInfo, tbEntMemberIdentify, identityType,
				entMemberInfoId,null);
		/**
		 * 创建会员认证资本信息
		 */
		createEntMemberIdentityCatpital(memberInfo, tbEntMemberIdentify, identityType);
		sendIdentifyMessage(bean.getMobile());
		return ResponseObject.successObject();
	}

	/**
	 * 创建会员认证资本信息
	 * 
	 * @param memberInfo
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private void createEntMemberIdentityCatpital(TbMemberInfo memberInfo, TbEntMemberIdentify tbEntMemberIdentify,
			EnterpriseIdentityType identityType) {
		Date date = new Date();
		long times = date.getTime();
		TbEntMemberIdentifyCapital tbEntMemberIdentifyCapital = new TbEntMemberIdentifyCapital();
		tbEntMemberIdentifyCapital.setId(tbEntMemberIdentify.getId());
		tbEntMemberIdentifyCapital.setMemberId(memberInfo.getId());
		tbEntMemberIdentifyCapital.setCompanyUid(tbEntMemberIdentify.getCompanyUid());
		tbEntMemberIdentifyCapital.setLeadsNumber(identityType.getLeadsNumber());
		tbEntMemberIdentifyCapital.setTotalLeadsNumber(identityType.getLeadsNumber());
		tbEntMemberIdentifyCapital.setTotalMemberNumber(identityType.getMemberNumber());
		tbEntMemberIdentifyCapital.setMemberNumber(identityType.getMemberNumber());
		tbEntMemberIdentifyCapital.setCoupon(identityType.getCoupon());
		tbEntMemberIdentifyCapital.setAddTime(times);
		tbEntMemberIdentifyCapital.setUpdateTime(times);
		tbEntMemberIdentifyCapital.setEnterpriseIdentyType(tbEntMemberIdentify.getIdentyType());
		Date expiresDate = DateTimeBusUtils.getExpiresYearDate(date);
		tbEntMemberIdentifyCapital.setStartTime(date);
		tbEntMemberIdentifyCapital.setExpiresTime(expiresDate);

		int rowEffected = tbEntMemberIdentifyCapitalMapper.insertSelective(tbEntMemberIdentifyCapital);
		if (rowEffected != 1) {
			throw new BusinessDataException("企业认证失败");
		}

		TbEntMemberIdentifyCapitalHis capitalHis = new TbEntMemberIdentifyCapitalHis();

		capitalService.updateCaptalHistory(tbEntMemberIdentifyCapital);

	}

	/**
	 * 创建会员企业信息
	 * 
	 * @param memberInfo
	 * @param tbEntMemberIdentify
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private TbEntMemberInfo createEntMemberInfo(TbMemberInfo memberInfo, TbEntMemberIdentify tbEntMemberIdentify,
			EnterpriseIdentityType identityType, long id, TbEntMemberInfo entMemberInfo) {

		TbEntMemberInfo tbEntMemberInfo = createEntMemberInfo(memberInfo, tbEntMemberIdentify, identityType.getValue(),
				id, (t) -> {
				}, entMemberInfo);
		if (tbEntMemberInfo == null) {
			throw new BusinessRuntimeException(BusinessMessages.MEMBER_IDENTIFY_FAILURE);
		}
		return tbEntMemberInfo;
	}

	/**
	 * 创建EntMemberInfo记录
	 * 
	 * @description
	 * @param memberInfo
	 *            基本用户信息
	 * @param tbEntMemberIdentify
	 *            mapper
	 * @param identityTypeValue
	 *            认证类型
	 * @param id
	 *            主键
	 * @param execute
	 *            函数方法
	 * @return boolean
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private TbEntMemberInfo createEntMemberInfo(TbMemberInfo memberInfo, TbEntMemberIdentify tbEntMemberIdentify,
			short identityTypeValue, long id, ExecuteFunction<TbEntMemberInfo> execute, TbEntMemberInfo entMemberInfo) {
		long times = System.currentTimeMillis();
		if(entMemberInfo!=null)
		{
			entMemberInfo.setEnterpriseIdentyType(identityTypeValue);
			entMemberInfo.setEnterprisePass(EnterprisePassStatus.Pass.getValue());
			entMemberInfo.setEnterpriseIdentyStatus(EnterpriseIdentifyStatus.Authenticated.getValue());
			execute.execute(entMemberInfo);
			int rowEffected = tbEntMemberInfoMapper.updateByPrimaryKeySelective(entMemberInfo);
			return rowEffected == 1 ? entMemberInfo : null;
		}
		TbEntMemberInfo tbEntMemberInfo = new TbEntMemberInfo();
		tbEntMemberInfo.setId(id);
		tbEntMemberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
		tbEntMemberInfo.setMemberId(memberInfo.getId());
		tbEntMemberInfo.setMemberUid(memberInfo.getUid());
		tbEntMemberInfo.setRealName(memberInfo.getRealname());
		tbEntMemberInfo.setMobile(memberInfo.getPhone());
		tbEntMemberInfo.setEmail(memberInfo.getEmail());
		tbEntMemberInfo.setMemberName(memberInfo.getUsername());
		tbEntMemberInfo.setCompanyUid(tbEntMemberIdentify.getCompanyUid());
		tbEntMemberInfo.setCompanyName(tbEntMemberIdentify.getFullName());
		tbEntMemberInfo.setEnterpriseManager(EnterpriseManagerType.Admin.getValue());
		tbEntMemberInfo.setEnterpriseIdentyType(identityTypeValue);
		tbEntMemberInfo.setEnterprisePass(EnterprisePassStatus.Pass.getValue());
		tbEntMemberInfo.setEnterpriseIdentyStatus(EnterpriseIdentifyStatus.Authenticated.getValue());
		tbEntMemberInfo.setAddTime(times);
		tbEntMemberInfo.setUpdateTime(times);
		execute.execute(tbEntMemberInfo);
		int rowEffected = tbEntMemberInfoMapper.insertSelective(tbEntMemberInfo);
		return rowEffected == 1 ? tbEntMemberInfo : null;
	}

	/**
	 * 创建或更新企业认证
	 * 
	 * @param memberInfo
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private TbEntMemberIdentify createOrUpdateEntIdentity(TbEntMemberIdentify identify, TbMemberInfo memberInfo,
			EnterpriseIdentityType identityType, String companyUid, String companyName, long entIdentifyId,
			long entMemberInfoId) {
		long times = System.currentTimeMillis();
		TbEntMemberIdentify queryIdentify = tbEntMemberIdentifyMapper.selectByCompanyUid(companyUid);
		if (queryIdentify != null && MemberInfoUtils.isIdentity(queryIdentify)) {
			throw new BusinessDataException("企业[" + queryIdentify.getFullName() + "]已经认证");
		}
		// TbEntMemberIdentify identify = new TbEntMemberIdentify();
		identify.setId(entIdentifyId);
		identify.setEntMemberId(entMemberInfoId);
		identify.setMemberId(memberInfo.getId());
		identify.setCompanyUid(companyUid);
		identify.setFullName(companyName);
		identify.setMemberName(memberInfo.getUsername());
		identify.setIdentyType(identityType.getValue());
		identify.setStatus(EnterpriseIdentifyStatus.Authenticated.getValue());
		// identify.setIdCardUrl(sourceEntTryoutInfo.getIdCardUrl());
		// identify.setBusinessLicenseUrl(sourceEntTryoutInfo.getBusinessLicenseUrl());
		identify.setUpdateTime(times);
		int rowEffected = 0;
		if (queryIdentify == null) {
			identify.setAddTime(times);
			rowEffected = tbEntMemberIdentifyMapper.insertSelective(identify);
		} else {
			rowEffected = tbEntMemberIdentifyMapper.updateByPrimaryKeySelective(identify);
		}
		if (rowEffected != 1) {
			throw new BusinessDataException("企业认证失败");
		}
		return identify;
	}

	/**
	 * 更改企业试用表状态
	 * 
	 * @param memberInfo
	 * @param sourceEntTryoutInfo
	 * @param tbEntMemberIdentify
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private void updateEntTryoutInfo(TbMemberInfo memberInfo, TbEntTryoutInfo sourceEntTryoutInfo,
			TbEntMemberIdentify tbEntMemberIdentify, long entMemberInfoId) {
		long times = System.currentTimeMillis();
		TbEntTryoutInfo entTryoutInfo = new TbEntTryoutInfo();
		entTryoutInfo.setId(sourceEntTryoutInfo.getId());
		entTryoutInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
		entTryoutInfo.setEntMemberId(entMemberInfoId);
		entTryoutInfo.setMemberId(memberInfo.getId());
		entTryoutInfo.setMemberName(memberInfo.getUsername());
		entTryoutInfo.setCompanyUid(tbEntMemberIdentify.getCompanyUid());
		entTryoutInfo.setCompanyName(tbEntMemberIdentify.getFullName());
		entTryoutInfo.setUpdateTime(times);
		entTryoutInfo.setStatus(EnterpriseTryoutStatus.ReviewPassed.getValue());
		int rowEffected = tbEntTryoutInfoMapper.updateByPrimaryKeySelective(entTryoutInfo);
		if (rowEffected != 1) {
			throw new BusinessDataException("企业认证失败");
		}
	}

	/**
	 * 更新或新建会员
	 * 
	 * @param bean
	 *            RequestEntIdentifyInfo
	 * @param times
	 *            时间
	 * @param sourceEntTryoutInfo
	 *            TbEntTryoutInfo
	 * @return TbMemberInfo
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private TbMemberInfo createOrUpdateMemberInfo(long memberId, String companyUid, String fullName, String mobile,
			String realName, long entMemberInfoId, long entIdentifyId) {
		int updateTime = DateTimeBusUtils.getTimeSecondsInt();
		TbMemberInfo sourceMemberInfo = null;
		if (memberId > 0) {
			sourceMemberInfo = tbMemberInfoMapper.selectByPrimaryKey(memberId);
		}
		/**
		 * 根据手机号码查询会员信息
		 */
		if (sourceMemberInfo == null) {
			sourceMemberInfo = tbMemberInfoMapper.selectByMobile(mobile);
		}
		if (sourceMemberInfo != null) {
			if (!sourceMemberInfo.getPhone().equals(mobile)) {
				throw new BusinessDataException("试用提交的的手机号码和当前认证会员的手机号码不一致!");
			}
			/**
			 * 没有默认企业关联,更新用户关联信息
			 */
			// if (!sourceMemberInfo.isEntIdentity())
			// {
			sourceMemberInfo.setEntMemberId(entMemberInfoId);
			TbMemberInfo tbMemberInfo = new TbMemberInfo();
			tbMemberInfo.setId(sourceMemberInfo.getId());
			tbMemberInfo.setEntMemberId(entMemberInfoId);
			tbMemberInfo.setEntIdentifyId(entIdentifyId);
			if (StringUtils.isNullOrEmpty(tbMemberInfo.getRealname())) {
				tbMemberInfo.setRealname(StringUtils.isNullSetEmpty(realName));
			}
			tbMemberInfo.setUpdateTime(updateTime);
			tbMemberInfo.setCompanyUid(companyUid);
			tbMemberInfo.setCompanyName(fullName);
			int rowEffected = tbMemberInfoMapper.updateByPrimaryKeySelective(tbMemberInfo);
			if (rowEffected != 1) {
				throw new BusinessDataException("企业认证失败");
			}
			// }

			return sourceMemberInfo;
		}

		/**
		 * 创建新的会员
		 */
		String raw = RandomUtils.randomString(6);
		TbMemberInfo tbMemberInfo = new TbMemberInfo();
		tbMemberInfo.setId(KeyGenerationUtils.generateKey());
		tbMemberInfo.setUid(UidGenerator.getUid(raw));
		tbMemberInfo.setRealname(realName);
		tbMemberInfo.setEmail("");
		tbMemberInfo.setUsername(mobile);
		tbMemberInfo.setPhone(mobile);
		tbMemberInfo.setCompanyUid(companyUid);
		tbMemberInfo.setCompanyName(fullName);
		tbMemberInfo.setEntMemberId(entMemberInfoId);
		tbMemberInfo.setEntIdentifyId(entIdentifyId);
		tbMemberInfo.setSalt(raw);
		tbMemberInfo.setAddTime(updateTime);
		tbMemberInfo.setUpdateTime(updateTime);

		int rowEffected = tbMemberInfoMapper.insertSelective(tbMemberInfo);
		if (rowEffected != 1) {
			throw new BusinessDataException("企业认证失败");
		}
		return tbMemberInfo;
	}

	/**
	 * 添加成员
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public TbMemberInfo addMember(RequestMemberInfo bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		capitalService.isCanAddMember(userInfo.getEntIdentifyId());
		TbMemberInfo adminInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
		TbEntMemberIdentify tbEntMemberIdentify = MemberRightsUtils.isAdminIdentity(tbEntMemberIdentifyMapper,
				userInfo.getEntIdentifyId(), adminInfo.getId());
		TbMemberInfo memberInfo = tbMemberInfoMapper.selectByMobile(bean.getMobile());
		// if (memberInfo != null) {
		// throw new BusinessException("手机号码[" + bean.getMobile() +
		// "]已经是系统会员,请选择认证");
		// }

		long memberId = memberInfo != null ? memberInfo.getId() : KeyGenerationUtils.generateKey();
		long entMemberInfoId = KeyGenerationUtils.generateKey();
		String salt = RandomUtils.randomString(6);
		String memberUid = UidGenerator.getUid(salt);

		long times = System.currentTimeMillis();
		TbEntMemberInfo tbEntMemberInfo = new TbEntMemberInfo();
		tbEntMemberInfo.setId(entMemberInfoId);
		tbEntMemberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
		tbEntMemberInfo.setMemberId(memberId);
		tbEntMemberInfo.setMemberUid(memberUid);
		tbEntMemberInfo.setMemberName(bean.getMobile());
		tbEntMemberInfo.setRealName(bean.getName());
		tbEntMemberInfo.setMobile(bean.getMobile());
		tbEntMemberInfo.setCompanyUid(tbEntMemberIdentify.getCompanyUid());
		tbEntMemberInfo.setCompanyName(tbEntMemberIdentify.getFullName());
		tbEntMemberInfo.setEnterpriseManager(EnterpriseManagerType.Normal.getValue());
		tbEntMemberInfo.setEnterpriseIdentyType(userInfo.getIdentify().getEnterpriseIdentyType());
		tbEntMemberInfo.setEnterprisePass(EnterprisePassStatus.Pass.getValue());
		tbEntMemberInfo.setEnterpriseIdentyStatus(EnterpriseIdentifyStatus.Authenticated.getValue());
		tbEntMemberInfo.setAddTime(times);
		tbEntMemberInfo.setUpdateTime(times);
		int rowEffected = tbEntMemberInfoMapper.insertSelective(tbEntMemberInfo);
		if (rowEffected != 1) {
			throw new BusinessDataException("添加成员失败");
		}

		int memTime = DateTimeBusUtils.getTimeSecondsInt(times);

		if (memberInfo == null) {
			memberInfo = new TbMemberInfo();
			memberInfo.setId(memberId);
			memberInfo.setUsername(bean.getMobile());
			memberInfo.setPhone(bean.getMobile());
			memberInfo.setRealname(bean.getName());
			memberInfo.setPosition(bean.getPosition());
			memberInfo.setSalt(salt);
			memberInfo.setUid(memberUid);
			memberInfo.setAddTime(memTime);
			memberInfo.setCompanyUid(adminInfo.getCompanyUid());
			memberInfo.setCompanyName(adminInfo.getCompanyName());
			memberInfo.setUpdateTime(memTime);
			memberInfo.setEntMemberId(entMemberInfoId);
			memberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
			rowEffected = tbMemberInfoMapper.insertSelective(memberInfo);
			if (rowEffected != 1) {
				throw new BusinessDataException("添加成员失败");
			}
		} else {
			memberInfo.setCompanyUid(adminInfo.getCompanyUid());
			memberInfo.setCompanyName(adminInfo.getCompanyName());
			if (StringUtils.isNullOrEmpty(memberInfo.getRealname())) {
				memberInfo.setRealname(StringUtils.isNullSetEmpty(bean.getName()));
			}

			if (StringUtils.isNullOrEmpty(memberInfo.getPosition())) {
				memberInfo.setPosition(StringUtils.isNullSetEmpty(bean.getPosition()));
			}

			memberInfo.setUpdateTime(memTime);
			memberInfo.setEntMemberId(entMemberInfoId);
			memberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
			rowEffected = tbMemberInfoMapper.updateByPrimaryKeySelective(memberInfo);
			if (rowEffected != 1) {
				throw new BusinessDataException("添加成员失败");
			}
		}

		return memberInfo;
	}

	/**
	 * 展示列表
	 * 
	 * @param bean
	 *            MemberQueryListBean
	 * @return List<MemberInfo>
	 */
	public List<MemberInfo> listMembers(MemberQueryListBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		bean.setCompanyUid(userInfo.getCompanyUid());
		List<MemberInfo> list = tbMemberInfoMapper.select(bean);

		List<Long> ids = list.stream().map((item) -> item.getMemberId()).collect(Collectors.toList());
		if (!ArrayUtils.isEmpty(ids)) {
			QueryEntAdminStatusBean entAdminStatusBean = new QueryEntAdminStatusBean();
			entAdminStatusBean.setEntIdentifyId(userInfo.getEntIdentifyId());
			entAdminStatusBean.setIds(ids);
			List<MemberInfo> entList = tbEntMemberInfoMapper.selectByEntIdentifyIdAndMemberid(entAdminStatusBean);
			for (MemberInfo item : list) {
				for (MemberInfo entItem : entList) {
					if (entItem.getMemberId().equals(item.getMemberId())) {
						item.setEnterpriseIdentyStatus(entItem.getEnterpriseIdentyStatus());
						item.setEntMemberId(entItem.getEntMemberId());
						item.setEnterpriseManager(entItem.getEnterpriseManager());
						item.setEnterprisePass(entItem.getEnterprisePass());
						item.setEnterpriseIdentyType(entItem.getEnterpriseIdentyType());
						item.setEntIdentifyId(entItem.getEntIdentifyId());
						item.setCompanyName(entItem.getCompanyName());
						item.setCompanyUid(entItem.getCompanyUid());
						break;
					}
				}
			}
		}
		bean.setResults(list);
		return list;
	}

	/**
	 * 开通企业版
	 * 
	 * @param bean
	 *            MemberIdentityBean
	 * @return ResponseObject
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject openEdition(MemberIdentityBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		capitalService.isCanAddMember(userInfo.getEntIdentifyId());

		TbMemberInfo adminInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
		if (adminInfo.getId().longValue() == bean.getMemberId()) {
			throw new BusinessException("已经是管理员");
		}
		TbEntMemberIdentify tbEntMemberIdentify = MemberRightsUtils.isAdminIdentity(tbEntMemberIdentifyMapper,
				userInfo.getEntIdentifyId(), adminInfo.getId());

		TbMemberInfo memberInfo = MemberInfoUtils.isMemberInfo(tbMemberInfoMapper, bean.getMemberId());
		TbEntMemberInfo entMemberInfo = null;
		QueryMemberInfo queryMemberInfo = new QueryMemberInfo();
		queryMemberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
		queryMemberInfo.setMemberId(memberInfo.getId());
		entMemberInfo = tbEntMemberInfoMapper.selectByIdentifyAndMemberId(queryMemberInfo);

		int rowEffected = 0;
		long entMemberId = KeyGenerationUtils.generateKey();
		
		TbEntMemberInfo tbEntMemberInfo = createEntMemberInfo(memberInfo, tbEntMemberIdentify,
				tbEntMemberIdentify.getIdentyType(), entMemberId, (t) -> {
					t.setEnterpriseManager(EnterpriseManagerType.Normal.getValue());
					
				}, entMemberInfo);
		if (tbEntMemberInfo == null) {
			throw new BusinessDataException("开通企业版失败");
		}
		
		TbMemberInfo updateMemberInfo = new TbMemberInfo();
		updateMemberInfo.setId(memberInfo.getId());
		updateMemberInfo.setUpdateTime(DateTimeBusUtils.getTimeSecondsInt());
		updateMemberInfo.setEntMemberId(tbEntMemberInfo.getId());
		updateMemberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
		rowEffected = tbMemberInfoMapper.updateByPrimaryKeySelective(updateMemberInfo);
		if (rowEffected != 1) {
			throw new BusinessDataException("开通企业版失败");
		}

		return new ResponseObject();
	}

	/**
	 * 关闭企业版
	 * 
	 * @param bean
	 *            MemberIdentityBean
	 * @return ResponseObject
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject closeEdition(MemberIdentityBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		TbMemberInfo adminInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
		if (adminInfo.getId().longValue() == bean.getMemberId()) {
			throw new BusinessException("管理员不能关闭自已的企业版");
		}
		TbEntMemberIdentify tbEntMemberIdentify = MemberRightsUtils.isAdminIdentity(tbEntMemberIdentifyMapper,
				userInfo.getEntIdentifyId(), adminInfo.getId());

		TbMemberInfo memberInfo = MemberInfoUtils.isMemberInfo(tbMemberInfoMapper, bean.getMemberId());
		int rowEffected = 0;
		long times = System.currentTimeMillis();

		/**
		 * 当前默认企业是要关闭的企业
		 */

		if (memberInfo.getEntIdentifyId().longValue() == userInfo.getEntIdentifyId()) {

			closeOrUnAuth(memberInfo, true, times, bean);

			// QueryMemberInfo queryMemberInfo = new QueryMemberInfo();
			// queryMemberInfo.setMemberId(memberInfo.getId());
			// queryMemberInfo.setEntMemberId(memberInfo.getEntMemberId());
			// TbEntMemberInfo otherEntMemberInfo =
			// tbEntMemberInfoMapper.selectByMemberIdAndExclude(queryMemberInfo);
			// int memberTime = DateTimeBusUtils.getTimeSecondsInt(times);
			// TbMemberInfo updateMemberInfo = new TbMemberInfo();
			// updateMemberInfo.setId(memberInfo.getId());
			// updateMemberInfo.setUpdateTime(memberTime);
			// if (otherEntMemberInfo != null) {
			// updateMemberInfo.setEntMemberId(otherEntMemberInfo.getId());
			// updateMemberInfo.setEntIdentifyId(otherEntMemberInfo.getEntIdentifyId());
			// } else {
			// updateMemberInfo.setEntIdentifyId(0L);
			// updateMemberInfo.setEntMemberId(0L);
			// }
			// rowEffected =
			// tbMemberInfoMapper.updateByPrimaryKeySelective(updateMemberInfo);
			// if (rowEffected != 1) {
			// throw new
			// BusinessRuntimeException(BusinessMessages.MEMBER_CLOSE_ENT_EDITION_FAILURE,bean);
			// }
		}

		TbEntMemberInfo updateEntMemberInfo = new TbEntMemberInfo();
		updateEntMemberInfo.setEntIdentifyId(userInfo.getEntIdentifyId());
		updateEntMemberInfo.setMemberId(memberInfo.getId());
		updateEntMemberInfo.setUpdateTime(times);
		rowEffected = tbEntMemberInfoMapper.closeEntEdition(updateEntMemberInfo);

		if (rowEffected != 1) {
			throw new BusinessRuntimeException(BusinessMessages.MEMBER_CLOSE_ENT_EDITION_FAILURE, bean);
		}

		try {
			RedisOperator.removeUserInfo(memberInfo.getId());
		} catch (Exception e) {
			throw new BusinessRuntimeException(BusinessMessages.MEMBER_CLOSE_ENT_EDITION_FAILURE, bean);
		}

		return new ResponseObject();
	}

	private void closeOrUnAuth(TbMemberInfo memberInfo, boolean isClose, long times, MemberIdentityBean bean) {
		QueryMemberInfo queryMemberInfo = new QueryMemberInfo();
		queryMemberInfo.setMemberId(memberInfo.getId());
		queryMemberInfo.setEntMemberId(memberInfo.getEntMemberId());
		List<TbEntMemberInfo> otherEntMemberInfos = tbEntMemberInfoMapper
				.selectByMemberIdAndExcludeList(queryMemberInfo);
		TbEntMemberInfo otherEntMemberInfo = ArrayUtils.isEmpty(otherEntMemberInfos) ? null
				: otherEntMemberInfos.get(0);
		int memberTime = DateTimeBusUtils.getTimeSecondsInt(times);
		TbMemberInfo updateMemberInfo = new TbMemberInfo();
		updateMemberInfo.setId(memberInfo.getId());
		updateMemberInfo.setUpdateTime(memberTime);
		if (otherEntMemberInfo != null) {
			updateMemberInfo.setEntMemberId(otherEntMemberInfo.getId());
			updateMemberInfo.setEntIdentifyId(otherEntMemberInfo.getEntIdentifyId());
		} else {
			updateMemberInfo.setEntIdentifyId(0L);
			updateMemberInfo.setEntMemberId(0L);
		}
		int rowEffected = tbMemberInfoMapper.updateByPrimaryKeySelective(updateMemberInfo);
		if (rowEffected != 1) {
			if (isClose) {
				throw new BusinessRuntimeException(BusinessMessages.MEMBER_CLOSE_ENT_EDITION_FAILURE, bean);
			} else {
				throw new BusinessRuntimeException(BusinessMessages.MEMBER_UNAUTH_FAILURE, bean);
			}
		}
	}

	/**
	 * 认证企业版会员
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject authenticate(MemberIdentityBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		TbMemberInfo adminInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
		if (adminInfo.getId().longValue() == bean.getMemberId()) {
			throw new BusinessException("管理员不能认证自己");
		}
		TbEntMemberIdentify tbEntMemberIdentify = MemberRightsUtils.isAdminIdentity(tbEntMemberIdentifyMapper,
				userInfo.getEntIdentifyId(), adminInfo.getId());

		TbMemberInfo memberInfo = MemberRightsUtils.isMemberInfo(tbMemberInfoMapper, bean.getMemberId());

		long entMemberInfoId = KeyGenerationUtils.generateKey();
		long times = System.currentTimeMillis();
		int rowEffected = 0;
		/**
		 * 更新会员状态
		 */

		TbEntMemberInfo entMemberInfo = null;
		QueryMemberInfo queryMemberInfo = new QueryMemberInfo();
		queryMemberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
		queryMemberInfo.setMemberId(memberInfo.getId());
		entMemberInfo = tbEntMemberInfoMapper.selectByIdentifyAndMemberId(queryMemberInfo);
		
		TbEntMemberInfo tbEntMemberInfo = createEntMemberInfo(memberInfo, tbEntMemberIdentify,
				tbEntMemberIdentify.getIdentyType(), entMemberInfoId, (t) -> {
					t.setEnterpriseManager(EnterpriseManagerType.Normal.getValue());
					t.setEnterprisePass(EnterprisePassStatus.UnPass.getValue());
				},entMemberInfo);

		if (tbEntMemberInfo == null) {
			throw new BusinessDataException("认证成员失败");
		}
		
		if (!memberInfo.isEntIdentity()) {
			TbEntMemberInfo tempEntMemberInfo = tbEntMemberInfoMapper.selectByPrimaryKey(memberInfo.getEntMemberId());
			/**
			 * 当前没有认证
			 */
			if (tempEntMemberInfo.isPassed() == false) {
				TbMemberInfo updateMemberInfo = new TbMemberInfo();
				updateMemberInfo.setId(memberInfo.getId());
				updateMemberInfo.setEntIdentifyId(tbEntMemberIdentify.getId());
				updateMemberInfo.setEntMemberId(tbEntMemberInfo.getId());
				updateMemberInfo.setUpdateTime(DateTimeBusUtils.getTimeSecondsInt(times));
				rowEffected = tbMemberInfoMapper.updateByPrimaryKeySelective(updateMemberInfo);
				if (rowEffected != 1) {
					return ResponseObject.userFailure("认证成员失败!");
				}
			}
		}

		return new ResponseObject();
	}

	/**
	 * 解除认证
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject unAuthenticate(MemberIdentityBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		TbMemberInfo adminInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
		if (adminInfo.getId().longValue() == bean.getMemberId()) {
			throw new BusinessException("管理员不能解除认证自己");
		}
		TbEntMemberIdentify tbEntMemberIdentify = MemberRightsUtils.isAdminIdentity(tbEntMemberIdentifyMapper,
				userInfo.getEntIdentifyId(), adminInfo.getId());

		Tuple<TbMemberInfo, TbEntMemberInfo> tuple = MemberRightsUtils.isMemberIdentify(tbMemberInfoMapper,
				tbEntMemberInfoMapper, bean.getMemberId(), userInfo.getCompanyUid());

		TbMemberInfo memberInfo = tuple.getK(); // MemberInfoUtils.isMemberInfo(tbMemberInfoMapper,
												// bean.getMemberId());
		int rowEffected = 0;
		long times = System.currentTimeMillis();
		/**
		 * 当前默认企业是要关闭的企业
		 */
		if (memberInfo.getEntIdentifyId().longValue() == userInfo.getEntIdentifyId()) {
			/**
			 * 查询当前用户认证的其它的企业
			 */
			closeOrUnAuth(memberInfo, false, times, bean);
		}
		/**
		 * 解除认证
		 */
		TbEntMemberInfo updateEntMemberInfo = new TbEntMemberInfo();
		updateEntMemberInfo.setEntIdentifyId(userInfo.getEntIdentifyId());
		updateEntMemberInfo.setMemberId(memberInfo.getId());
		updateEntMemberInfo.setUpdateTime(times);
		rowEffected = tbEntMemberInfoMapper.unAuth(updateEntMemberInfo);
		if (rowEffected != 1) {
			throw new BusinessRuntimeException(BusinessMessages.MEMBER_UNAUTH_FAILURE, bean);
		}

		TbEntMemberInfo entMemberInfo = tuple.getV();

		try {
			RedisOperator.removeUserInfo(memberInfo.getId());
		} catch (Exception e) {
			throw new BusinessRuntimeException(BusinessMessages.MEMBER_UNAUTH_FAILURE, bean);
		}
		return new ResponseObject();
	}

	/**
	 * 转移管理员
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject transferManager(MemberIdentityBean bean) {
		UserInfo userInfo = LoginAuth.getUserInfo();
		if (userInfo.getId() == bean.getMemberId()) {
			throw new BusinessException("不能转移管理员给自己");
		}
		TbMemberInfo adminInfo = MemberRightsUtils.isAdmin(tbMemberInfoMapper);
		TbEntMemberIdentify tbEntMemberIdentify = MemberRightsUtils.isAdminIdentity(tbEntMemberIdentifyMapper,
				userInfo.getEntIdentifyId(), adminInfo.getId());

		TbMemberInfo memberInfo = MemberRightsUtils.isMemberIdentify(tbMemberInfoMapper);
		QueryMemberInfo queryMemberInfo = new QueryMemberInfo();
		queryMemberInfo.setMemberId(memberInfo.getId());
		queryMemberInfo.setCompanyUid(userInfo.getCompanyUid());
		TbEntMemberInfo entMemberInfo = tbEntMemberInfoMapper.selectByMemberIdAndCompanyUid(queryMemberInfo);
		if (entMemberInfo == null) {
			throw new BusinessException("成员[" + memberInfo.getUsername() + "]不是企业会员");
		}

		long times = System.currentTimeMillis();
		int rowEffected = 0;

		TbEntMemberIdentify tMemberIdentify = new TbEntMemberIdentify();
		tMemberIdentify.setId(tbEntMemberIdentify.getId());
		tMemberIdentify.setMemberId(memberInfo.getId());
		tMemberIdentify.setEntMemberId(entMemberInfo.getId());
		tMemberIdentify.setMemberName(memberInfo.getUsername());
		tMemberIdentify.setMobile(memberInfo.getPhone());
		tMemberIdentify.setPosition(memberInfo.getPosition());
		tMemberIdentify.setRealName(memberInfo.getRealname());
		tMemberIdentify.setUpdateTime(System.currentTimeMillis());
		rowEffected = tbEntMemberIdentifyMapper.updateByPrimaryKeySelective(tMemberIdentify);
		if (rowEffected != 1) {
			return ResponseObject.userFailure("转移管理员失败!");
		}

		TbEntMemberInfo tbEntMemberInfoAdmin = new TbEntMemberInfo();
		tbEntMemberInfoAdmin.setId(adminInfo.getEntMemberId());
		tbEntMemberInfoAdmin.setEnterpriseManager(EnterpriseManagerType.Normal.getValue());
		tbEntMemberInfoAdmin.setEnterprisePass(EnterprisePassStatus.Pass.getValue());
		tbEntMemberInfoAdmin.setEnterpriseIdentyStatus(EnterpriseIdentifyStatus.Authenticated.getValue());
		tbEntMemberInfoAdmin.setUpdateTime(times);
		rowEffected = tbEntMemberInfoMapper.updateByPrimaryKeySelective(tbEntMemberInfoAdmin);
		if (rowEffected != 1) {
			return ResponseObject.userFailure(BusinessMessages.MEMBER_ADMIN_TRANSFER_FAILURE);
		}

		TbEntMemberInfo tbEntMemberInfo = new TbEntMemberInfo();
		tbEntMemberInfo.setId(entMemberInfo.getId());
		tbEntMemberInfo.setEnterpriseManager(EnterpriseManagerType.Admin.getValue());
		tbEntMemberInfo.setEnterprisePass(EnterprisePassStatus.Pass.getValue());
		tbEntMemberInfo.setEnterpriseIdentyStatus(EnterpriseIdentifyStatus.Authenticated.getValue());
		tbEntMemberInfo.setUpdateTime(times);
		rowEffected = tbEntMemberInfoMapper.updateByPrimaryKeySelective(tbEntMemberInfo);
		if (rowEffected != 1) {
			return ResponseObject.userFailure(BusinessMessages.MEMBER_ADMIN_TRANSFER_FAILURE);
		}

		TbEntMemberIdentifyCapital capital = new TbEntMemberIdentifyCapital();
		capital.setId(tbEntMemberIdentify.getId());
		capital.setMemberId(memberInfo.getEntMemberId());
		rowEffected = tbEntMemberIdentifyCapitalMapper.updateByPrimaryKeySelective(capital);
		if (rowEffected != 1) {
			return ResponseObject.userFailure(BusinessMessages.MEMBER_ADMIN_TRANSFER_FAILURE);
		}

		return new ResponseObject("转移管理员成功");
	}

	/**
	 * 提交试用表单
	 * 
	 * @return ResponseObject
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	public ResponseObject tryoutSubmit(RequestTrySubmitBean bean) {
		String code = RedisOperator.getTryoutVerifyCode(bean.getMobile());
		if (!bean.getCode().equals(code)) {
			return ResponseObject.userFailure("验证码错误");
		}
		long id = KeyGenerationUtils.generateKey();
		TbEntTryoutInfo entity = new TbEntTryoutInfo();
		entity.setId(id);
		entity.setSourceCompanyName(bean.getCompanyName());
		entity.setAccount(bean.getAccount());
		entity.setName(bean.getRealname());
		entity.setEmail(bean.getEmail());
		entity.setMobile(bean.getMobile());
		entity.setPosition(bean.getPosition());
		entity.setStatus(EnterpriseTryoutStatus.WaitingForReview.getValue());
		long time = System.currentTimeMillis();
		entity.setAddTime(time);
		entity.setUpdateTime(time);
		int rowEffected = tbEntTryoutInfoMapper.insertSelective(entity);
		if (rowEffected != 1) {
			throw new BusinessException("提交试用申请失败");
		}
		RedisOperator.removeTryoutVerifyCode(bean.getMobile());
		return new ResponseObject(BuildConfig.isProduction() ? null : id);
	}

	/**
	 * 认证公司列表
	 */
	@Override
	public ResponseObject listIdentify(RequestMemberIdentifyBean bean) {
		List<TbEntMemberIdentify> results = tbEntMemberIdentifyMapper.select(bean);
		bean.setResults(results);
		return new ResponseObject(bean);
	}

}
